<template>
  <div class="skill-overview-page">
    <div class="page-header">
      <h2>技能总览</h2>
      <p>查看所有维修工的技能分布情况</p>
    </div>

    <!-- 搜索表单 -->
    <a-card class="search-card">
      <a-form :model="searchForm" layout="inline" @submit="handleSearch">
        <a-form-item label="维修工姓名">
          <a-input
            v-model:value="searchForm.nickName"
            placeholder="请输入维修工姓名"
            style="width: 200px"
          />
        </a-form-item>
        <a-form-item label="维修工账号">
          <a-input
            v-model:value="searchForm.accountName"
            placeholder="请输入维修工账号"
            style="width: 200px"
          />
        </a-form-item>
        <a-form-item label="技能类别">
          <a-select
            v-model:value="searchForm.categoryName"
            placeholder="请选择技能类别"
            style="width: 200px"
            allow-clear
          >
            <a-select-option
              v-for="category in categoryList"
              :key="category.id"
              :value="category.categoryName"
            >
              {{ category.categoryName }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item>
          <a-space>
            <a-button type="primary" html-type="submit" :loading="loading"> 搜索</a-button>
            <a-button @click="resetSearch">重置</a-button>
          </a-space>
        </a-form-item>
      </a-form>
    </a-card>

    <!-- 技能统计 -->
    <a-card title="技能统计" class="stats-card">
      <a-row :gutter="16">
        <a-col :span="6">
          <a-statistic title="维修工总数" :value="skillStats.totalMaintenanceWorkers" />
        </a-col>
        <a-col :span="6">
          <a-statistic title="有技能的维修工" :value="skillStats.skilledMaintenanceWorkers" />
        </a-col>
        <a-col :span="6">
          <a-statistic title="技能类别总数" :value="skillStats.totalSkills" />
        </a-col>
        <a-col :span="6">
          <a-statistic title="技能分配总数" :value="skillStats.totalSkillAssignments" />
        </a-col>
      </a-row>
    </a-card>

    <!-- 技能列表 -->
    <a-card title="技能分配详情" class="skill-list-card">
      <a-table
        :columns="columns"
        :data-source="skillList"
        :loading="loading"
        :pagination="paginationConfig"
        @change="handleTableChange"
        :scroll="{ x: 1200, y: 800 }"
        row-key="id"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'userInfo'">
            <div class="user-info">
              <div class="user-name">{{ record.nickName }}</div>
              <div class="user-account">{{ record.accountName }}</div>
            </div>
          </template>
          <template v-if="column.key === 'contact'">
            <div class="contact-info">
              <div>{{ record.email }}</div>
              <div>{{ record.phoneNumber }}</div>
            </div>
          </template>
          <template v-if="column.key === 'skills'">
            <div class="skills-tags">
              <!--v-for="skill in getWorkerSkills(record.userId)"-->
              <!--:key="skill.categoryId"-->
              <a-tag color="blue">
                {{ record.categoryName }}
              </a-tag>
              <span v-if="getWorkerSkills(record.userId).length === 0" class="no-skills">
                暂无技能
              </span>
            </div>
          </template>
          <template v-if="column.key === 'actions'">
            <a-space>
              <a-button type="link" size="small" @click="viewWorkerSkills(record)">
                查看详情
              </a-button>
              <a-button type="link" size="small" @click="manageWorkerSkills(record)">
                管理技能
              </a-button>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 技能详情弹窗 -->
    <a-modal
      v-model:open="skillDetailModalVisible"
      :title="`${selectedWorkerDetail?.nickName} 的技能详情`"
      :footer="null"
      width="600px"
    >
      <div v-if="selectedWorkerDetail" class="skill-detail-content">
        <div class="worker-info-detail">
          <h4>维修工信息</h4>
          <p><strong>姓名：</strong>{{ selectedWorkerDetail.nickName }}</p>
          <p><strong>账号：</strong>{{ selectedWorkerDetail.accountName }}</p>
          <p><strong>邮箱：</strong>{{ selectedWorkerDetail.email }}</p>
          <p><strong>电话：</strong>{{ selectedWorkerDetail.phoneNumber }}</p>
        </div>

        <div class="skills-detail">
          <h4>技能列表</h4>
          <div v-if="getWorkerSkills(selectedWorkerDetail.userId).length > 0">
            <div
              v-for="skill in getWorkerSkills(selectedWorkerDetail.userId)"
              :key="skill.categoryId"
              class="skill-detail-item"
            >
              <div class="skill-name">{{ skill.categoryName }}</div>
              <div class="skill-desc">{{ skill.categoryDescription }}</div>
            </div>
          </div>
          <a-empty v-else description="暂无技能" />
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import { getMaintenanceSkillList, getSkillStats } from '@/api/skill'
import { getCategoryList } from '@/api/category'
import type {
  MaintenanceSkillResponse,
  RepairCategory,
  MaintenanceSkillQueryRequest,
  SkillStatsResponse,
  PageResponse,
  PaginationState
} from '@/types'
import { createPaginationFromResponse, handlePaginationNavigation } from '@/utils/pagination'

const router = useRouter()

// 表格列定义
const columns = [
  {
    title: '维修工信息',
    key: 'userInfo',
    width: 200,
  },
  {
    title: '联系方式',
    key: 'contact',
    width: 200,
  },
  {
    title: '技能',
    key: 'skills',
    width: 300,
    ellipsis: true,
  },
  {
    title: '操作',
    key: 'actions',
    width: 150,
    fixed: 'right' as const,
  },
]

// 响应式数据
const loading = ref(false)
const skillList = ref<MaintenanceSkillResponse[]>([])
const categoryList = ref<RepairCategory[]>([])
const skillDetailModalVisible = ref(false)
const selectedWorkerDetail = ref<MaintenanceSkillResponse | null>(null)
const skillStats = ref<SkillStatsResponse>({
  totalMaintenanceWorkers: 0,
  skilledMaintenanceWorkers: 0,
  totalSkills: 0,
  totalSkillAssignments: 0
})

// 搜索表单
const searchForm = reactive<MaintenanceSkillQueryRequest>({
  accountName: '',
  nickName: '',
  categoryName: '',
  pageSize: 10,
  current: 1,
  lastId: 0,
})

// 分页状态管理
const paginationState = ref<PaginationState>({
  current: 1,
  pageSize: 10,
  total: 0,
  pages: 0,
  hasNext: false,
  nextCursor: 0,
  previousPageCursors: []
})

// 分页配置
const paginationConfig = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number, range: [number, number]) =>
    `第 ${range[0]}-${range[1]} 条，共 ${total} 条`,
})

// 当前页面的起始lastId
const currentPageLastId = ref(0)

// 获取技能统计数据
const fetchSkillStats = async () => {
  try {
    const response = await getSkillStats()
    if (response.code === 0) {
      skillStats.value = response.data
    } else {
      message.error('获取技能统计失败')
    }
  } catch (error) {
    console.error('获取技能统计失败:', error)
    message.error('获取技能统计失败')
  }
}

// 页面初始化
onMounted(() => {
  fetchSkillList()
  fetchCategories()
  fetchSkillStats()
})

// 获取技能列表
const fetchSkillList = async (resetPagination = false, useLastId?: number) => {
  try {
    loading.value = true

    if (resetPagination) {
      // 重置分页状态
      paginationState.value = {
        current: 1,
        pageSize: searchForm.pageSize || 10,
        total: 0,
        pages: 0,
        hasNext: false,
        nextCursor: 0,
        previousPageCursors: []
      }
      currentPageLastId.value = 0
    }

    const queryParams = { ...searchForm }
    queryParams.pageSize = paginationState.value.pageSize
    queryParams.current = paginationState.value.current
    queryParams.lastId = useLastId !== undefined ? useLastId : currentPageLastId.value

    const response = await getMaintenanceSkillList(queryParams)
    if (response.code === 0 && response.data) {
      const pageData = response.data as PageResponse<MaintenanceSkillResponse>

      // 更新数据源
      skillList.value = pageData.records || []

      // 更新分页状态
      paginationState.value = {
        current: pageData.current,
        pageSize: pageData.size,
        total: pageData.total,
        pages: pageData.pages,
        hasNext: pageData.hasNext,
        nextCursor: pageData.nextCursor,
        previousPageCursors: paginationState.value.previousPageCursors
      }

      // 更新分页配置
      const paginationConfigData = createPaginationFromResponse(pageData)
      Object.assign(paginationConfig, paginationConfigData)
    } else {
      message.error('获取技能列表失败')
    }
  } catch (error) {
    console.error('获取技能列表失败:', error)
    message.error('获取技能列表失败')
  } finally {
    loading.value = false
  }
}

// 获取维修类别列表（只获取启用的）
const fetchCategories = async () => {
  try {
    const response = await getCategoryList({
      pageSize: 100,
      current: 1,
      lastId: 0,
      isActive: 1, // 只获取启用的类别
    })
    if (response.code === 0 && response.data) {
      // 处理新的分页响应结构
      const pageData = response.data
      categoryList.value = pageData.records || []
    }
  } catch (error) {
    console.error('获取维修类别失败:', error)
  }
}

// 获取指定维修工的技能列表
const getWorkerSkills = (userId: number) => {
  return skillList.value.filter((skill) => skill.userId === userId)
}

// 搜索
const handleSearch = () => {
  fetchSkillList(true)
}

// 重置搜索
const resetSearch = () => {
  Object.assign(searchForm, {
    accountName: '',
    nickName: '',
    categoryName: '',
    pageSize: 10,
    current: 1,
    lastId: 0,
  })
  fetchSkillList(true)
}

// 表格变化处理
const handleTableChange = (pag: any) => {
  const isNextPage = pag.current > paginationState.value.current
  const isPrevPage = pag.current < paginationState.value.current

  // 更新页面大小
  if (pag.pageSize !== paginationState.value.pageSize) {
    searchForm.pageSize = pag.pageSize
    paginationState.value.pageSize = pag.pageSize
    fetchSkillList(true) // 页面大小变化时重置分页
    return
  }

  if (isNextPage && paginationState.value.hasNext) {
    // 向前翻页
    const navResult = handlePaginationNavigation(
      paginationState.value,
      'next',
      currentPageLastId.value
    )

    paginationState.value.current = navResult.current
    paginationState.value.previousPageCursors = navResult.previousCursors
    currentPageLastId.value = navResult.lastId

    fetchSkillList(false, navResult.lastId)
  } else if (isPrevPage && paginationState.value.current > 1) {
    // 向后翻页
    const navResult = handlePaginationNavigation(
      paginationState.value,
      'prev',
      currentPageLastId.value
    )

    paginationState.value.current = navResult.current
    paginationState.value.previousPageCursors = navResult.previousCursors
    currentPageLastId.value = navResult.lastId

    fetchSkillList(false, navResult.lastId)
  }
}

// 查看维修工技能详情
const viewWorkerSkills = (record: MaintenanceSkillResponse) => {
  selectedWorkerDetail.value = record
  skillDetailModalVisible.value = true
}

// 管理维修工技能（跳转到技能管理页面）
const manageWorkerSkills = (record: MaintenanceSkillResponse) => {
  router.push({
    path: '/skill/manage',
    query: { workerId: record.userId },
  })
}
</script>

<style scoped>
.skill-overview-page {
  padding: 24px;
}

.page-header {
  margin-bottom: 24px;
}

.page-header h2 {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
}

.page-header p {
  margin: 0;
  color: #666;
}

.search-card {
  margin-bottom: 16px;
}

.search-card .ant-form {
  gap: 16px;
}

.stats-card {
  margin-bottom: 16px;
}

.skill-list-card {
  margin-bottom: 16px;
}

.user-info {
  line-height: 1.4;
}

.user-name {
  font-weight: 600;
  margin-bottom: 4px;
}

.user-account {
  color: #666;
  font-size: 12px;
}

.contact-info {
  line-height: 1.4;
  font-size: 12px;
  color: #666;
}

.skills-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

.no-skills {
  color: #999;
  font-size: 12px;
}

.skill-detail-content {
  padding: 16px 0;
}

.worker-info-detail {
  margin-bottom: 24px;
  padding: 16px;
  background-color: #fafafa;
  border-radius: 6px;
}

.worker-info-detail h4 {
  margin: 0 0 12px 0;
}

.worker-info-detail p {
  margin: 8px 0;
}

.skills-detail h4 {
  margin-bottom: 16px;
}

.skill-detail-item {
  padding: 12px;
  border: 1px solid #f0f0f0;
  border-radius: 6px;
  margin-bottom: 8px;
}

.skill-name {
  font-weight: 600;
  margin-bottom: 4px;
}

.skill-desc {
  color: #666;
  font-size: 12px;
}
</style>
